package com.example.threadlocaldemo0.service;

import com.example.threadlocaldemo0.dao.AllDao;
import com.example.threadlocaldemo0.utils.ConnectionContainer;
import com.example.threadlocaldemo0.utils.JdbcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;

@Service
public class OrderService {

    @Autowired
    private AllDao allDao;

    @Autowired
    private DataSource dataSource;

    public void placeOrder(String userId, String commodityCode, Integer count, Integer money) {

        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);

            ConnectionContainer.setConnection(conn);

            allDao.insertOrder(userId, commodityCode, count, money);
            allDao.updateAccount(userId, money);
            allDao.updateStorage(commodityCode, count);
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtils.quietlyRollback(conn);
        } finally {
            JdbcUtils.quietlyClose(conn);
        }

    }

}